{% extends "base.html" %}
{% import "_my_wtf_macros.html" as my_wtf_macros %}

{% block title %}万屏时代报价工具--编辑产品{% endblock %}

{% block panel_heading %}
    万屏时代报价工具--编辑产品
{% endblock %}

{% block panel_body %}
    <form id="add-product-form"
          action="{{ url_for('product_bp.edit_product', product_id=product.id) }}"
          method="post" class="form" role="form" onsubmit="on_form_submit()">
        {{ form.hidden_tag() }}
        {{ my_wtf_macros.form_field(form.product_type_id, div_col=6, label_col=3, field_col=9, readonly=true) }}
        <div class="clearfix visible-xs-block visible-sm-block visible-md-block visible-lg-block"></div>

        {{ my_wtf_macros.form_field(form.brand_id, div_col=6, label_col=3, field_col=9) }}
        {{ my_wtf_macros.form_field(form.brand_model_id, div_col=6, label_col=3, field_col=9) }}
        <div class="clearfix visible-xs-block visible-sm-block visible-md-block visible-lg-block"></div>

        {{ my_wtf_macros.form_field(form.price, div_col=6, label_col=3, field_col=9) }}
        {{ my_wtf_macros.form_field(form.suggest_price, div_col=6, label_col=3, field_col=9) }}
        <div class="clearfix visible-xs-block visible-sm-block visible-md-block visible-lg-block"></div>

        {{ my_wtf_macros.form_field(form.source, div_col=6, label_col=3, field_col=9) }}
        {{ my_wtf_macros.form_field(form.weight, div_col=6, label_col=3, field_col=9) }}
        <div class="clearfix visible-xs-block visible-sm-block visible-md-block visible-lg-block"></div>

        <div class="well well-sm">
            产品图片
            <div class="pull-right btn-group">
                <a href="#" id="add-product-pictures"
                   class="btn btn-xs btn-success"
                   style="margin-right: 5px;" target="_self">
                    添加图片
                </a>
            </div>
        </div>
        <div class="container form-group">
            <ul id="picture-container">
                {% for each in product.pictures or [] %}
                    <li class="pull-left"
                        style="position:relative; margin-top: 10px; margin-right: 10px;list-style:none; border:1px solid #DDD">
                        <i class="glyphicon glyphicon-remove text-red remove-image-btn"
                           aria-hidden="true"
                           style="position: absolute; right: 5px; top:3px;"
                           onclick="remove_picture(this)"
                        ></i>

                        <img src="{{ each }}" data-url="{{ each }}"
                             class="picture-url"
                             style="width: 150px; height: 150px">
                    </li>
                {% endfor %}
            </ul>
        </div>
        <br>

        <div id="product_params_container">
            {% if product_params %}
                <div class="well well-sm">技术参数
                    <div class="pull-right btn-group">
                        <button type="button" class="btn btn-xs btn-primary"
                                id="sync-param-btn" data-id={{ product.id }}
                                        data-product_type_id={{ product.product_type_id }}
                        >
                            同步技术参数
                        </button>
                    </div>

                </div>
            {% endif %}
            {% for each in product_params %}
                <div class="form-group col-xs-6 ">
                    <div class="row">
                        <label class="control-label  col-xs-3" for="param_name">
                            技术参数名{% if each.is_display %}(标题){% endif %}</label>
                        <div class="col-xs-9">
                            <input class="form-control" id="param_name"
                                   name="param_name" type="text" disabled="true"
                                   value="{{ each.name }}">
                        </div>
                    </div>
                </div>

                <div class="form-group col-xs-6 {% if each.is_required %}required{% endif %}">
                    <div class="row">
                        <label class="control-label  col-xs-4" for="spec_value">技术参数值（{{ each.unit_display }}）
                        </label>
                        <div class="col-xs-8">
                            <input class="form-control param_input"
                                   id="param_value" name="param_value"
                                   type="text"
                                   value="{{ each.value }}"
                                   data-id={{ each.id }} data-unit="{{ each.unit }}">
                        </div>
                    </div>
                </div>
            {% endfor %}
        </div>

        <div id="product_specs_container">
            <div class="clearfix visible-xs-block visible-sm-block visible-md-block visible-lg-block"></div>
            <div class="well well-sm">
                产品规格
                <div class="pull-right btn-group">
                    <button type="button" class="btn btn-xs btn-primary"
                            id="sync-spec-btn" data-id={{ product.id }}
                                    data-product_type_id={{ product.product_type_id }}
                    >
                        同步产品规格
                    </button>
                </div>
            </div>
            {% if product.spec_settings %}
                {% for each in product.spec_settings %}
                    <div class="form-group col-xs-6 ">
                        <div class="row">
                            <label class="control-label  col-xs-3"
                                   for="spec_name">
                                规格名</label>
                            <div class="col-xs-9">
                                <input class="form-control" id="spec_name"
                                       name="spec_name" type="text"
                                       disabled="true"
                                       value='{{ each.name }}  选项：{% if not each.is_input_type and each.options %} {{ each.options | to_json_ascii_false }}{% endif %}'>
                            </div>
                        </div>
                    </div>

                    <div class="form-group col-xs-6 ">
                        <div class="row">
                            <label class="control-label  col-xs-3"
                                   for="spec_value">规格值（{{ each.unit_display }}）
                            </label>
                            <div class="col-xs-9">
                                <input class="form-control spec_input"
                                       id="spec_value" name="spec_value"
                                       type="text"
                                       value='{{ each['values'] | to_json_ascii_false }}'
                                       data-spec_templates_id={{ each.spec_templates_id or each.id}}>
                            </div>
                        </div>
                    </div>
                {% endfor %}
            {% endif %}
        </div>
        <button type="submit" class="btn btn-success pull-right"
                id="add-demand-btn">
            保存
        </button>

        </div>

    </form>

    <form action="" id="picture-file-form">
        <input class="form-control" type="file" style="display:none"
               id="image_file"
               name="image_file" value=""
               accept=".jpg,.jpeg,.png,.bmp,.JPG,.JPEG,.BMG,.PNG"
        >
    </form>


{% endblock %}


{% block scripts %}
    {{ super() }}
    <script>
        function remove_picture(obj) {
            $(obj).parent().remove();
        }

        function on_form_submit() {
            add_params();
            add_pictures();
            add_specs();
        }

        function add_pictures() {
            var pictures = [];
            $('.picture-url').each(function () {
                pictures.push($(this).data('url'));
            });
            $('#pictures').val(JSON.stringify(pictures));
        }

        function add_params() {
            var params = [];
            $('.param_input').each(function () {
                var spec = {};
                spec.technology_param_id = $(this).data('id');
                spec.name = $(this).data('name');
                spec.value = $(this).val();
                spec.unit = $(this).data('unit');
                spec.calculate_item = $(this).data('calculate_item');
                spec.is_display = $(this).data('is_display');
                params.push(spec);
            });
            $('#params').val(JSON.stringify(params));
        }

        function add_specs() {
            var specs = {};
            $('.spec_input').each(function () {
                specs[$(this).data('spec_templates_id')] = $(this).val();
            });
            $('#specs').val(JSON.stringify(specs));
        }

        // 同步技术参数
        $('#sync-param-btn').click(
            function () {
                var product_id = $(this).data('id');
                var product_type_id = $(this).data('product_type_id');
                $.ajax({
                    url: "{{ url_for('product_bp.ajax_sync_params')}}",
                    data: JSON.stringify({
                        'product_id': product_id,
                        'product_type_id': product_type_id
                    }),
                    type: 'post',
                    dataType: 'json',
                    contentType: 'application/json',
                    cache: true
                }).done(function (data) {
                    if (!data.status) {
                        location.reload();
                    }
                    else {
                        alert("同步失败")
                    }

                }).fail(function () {
                    alert("获取产品规格失败，请联系系统管理员!")
                });
            }
        );

        function get_models_by_brand() {
            var brand_id = $('#brand_id').val();
            $.ajax({
                url: "{{ url_for('product_bp.ajax_brand_model_choices')}}",
                data: JSON.stringify({
                    'brand_id': brand_id
                }),
                type: 'post',
                dataType: 'json',
                contentType: 'application/json',
                cache: true
            }).done(function (data) {
                $("#brand_model_id").empty();
                for (var i = 0; i < data.length; i++) {
                    var id = data[i][0];
                    var name = data[i][1];
                    $("#brand_model_id").append(
                        "<option value='" + id + "'>" + name + "</option>"
                    );
                }

            }).fail(function () {
                $(obj).data('content', '服务器错误');
                $(obj).popover('show');
            });
        }

        // 同步产品规格
        $('#sync-spec-btn').click(
            function () {
                var product_id = $(this).data('id');
                var product_type_id = $(this).data('product_type_id');
                $.ajax({
                    url: "{{ url_for('product_bp.ajax_sync_specs')}}",
                    data: JSON.stringify({
                        'product_id': product_id,
                        'product_type_id': product_type_id
                    }),
                    type: 'post',
                    dataType: 'json',
                    contentType: 'application/json',
                    cache: true
                }).done(function (data) {
                    if (!data.status) {
                        location.reload();
                    }
                    else {
                        alert("同步失败")
                    }

                }).fail(function () {
                    alert("获取产品规格失败，请联系系统管理员!")
                });
            }
        );

        $('#add-product-pictures').click(function () {
            $('#image_file').click();
        });

        $('#image_file').change(function () {
            var form = new FormData(document.getElementById("picture-file-form"));
            var container = $("#picture-container");
            $.ajax({
                url: "{{ url_for('product_bp.ajax_upload_picture') }}",
                data: form,
                type: 'post',
                accept: 'application/json',
                processData: false,
                contentType: false,
                success: function (data) {
                    if (!data.status) {
                        container.append(
                            '<li class="pull-left" style="position:relative; margin-top: 10px; margin-right: 10px;list-style:none; border:1px solid #DDD">' +
                            '<i class="glyphicon glyphicon-remove text-red"' +
                            'aria-hidden="true" style="position: absolute; right: 5px; top:3px;" onclick="remove_picture(this)"></i> <img class="picture-url" src="' +
                            data.url + '" data-url="' + data.url + '" style="width: 150px; height: 150px"> </li>'
                        );
                        $('#image_file').empty();
                    }
                    else {
                        console.log('文件不能为空');
                    }

                }
            })
        });

        $(document).ready(function () {

            $("#brand_id").change(function () {
                get_models_by_brand();
            });
        })

    </script>

{% endblock %}
